<template>
  <div class="wrap">
    <img :src="qrImg" alt="" class="qrcode" v-if="qrImg" />
    <img :src="qrImg" alt="" class="qrcode qrcode_right" v-if="qrImg" />

    <!-- <button id="fullscreenBtn">全屏</button> -->
    <div class="worship-item" :class="[infoData.InteractiveMode == 1 ? 'start_bg' : '']" :id="`box_${index}`"
      v-for="(item, index) in boxList" :key="index">
      <div class="text-wrap">
        <p class="left">{{ item.ForwhomName }}：</p>
        <p class="content">{{ item.QifuContent }}</p>
        <p class="right">{{ item.QifuName }}</p>
      </div>
    </div>
    <img :src="infoData.BackgroundMaterialShow" id="img_mater" class="mater" ref="materialImg"
      v-if="infoData.isMaterialImg" />
    <video id="videoBox" class="mater" ref="materialVideo" controls autoplay loop preload="auto"
      :src="infoData.BackgroundMaterialShow" v-if="infoData.isMaterialVideo">
    </video>

    <img :src="infoData.BackgroundImageShow" class="wrap_bg video_bg" v-if="infoData.isBackImg" />
    <audio class="audio_wrap" ref="audioref" :src="`${infoData.backgroundMusic}`" controls autoplay loop>
    </audio>
    <video class="video_bg" ref="bgVideo" preload="auto" :poster="poster" :src="infoData.BackgroundImageShow" autoplay
      loop v-if="!infoData.isBackImg">
    </video>
  </div>
</template>
<script setup name="worship">
import QRCode from 'qrcode'
import axios, { baseUrl, webBaseUrl } from '../utils/http'
import { checkImgExists, checkVideoExists, checkAudioExists } from '../utils/util'

import { onMounted, ref, onBeforeUnmount, watch, nextTick } from 'vue';
import gsap from "gsap";
import { MotionPathPlugin } from "gsap/MotionPathPlugin";
//import poster from '@/assets/img/grey.png'

const infoData = ref({})
const qrImg = ref('')
const boxList = ref([])
let animations = [];
let timer = null
const lid = ref(0)
const audioref = ref(null)
const bgVideo = ref(null)
const poster = ref('')

const props = defineProps({
  data: {
    type: Object,
    default: () => { }
  }
})
gsap.registerPlugin(MotionPathPlugin);
// With async/await
const generateQR = async text => {
  try {
    const qr = await QRCode.toDataURL(text)
    //console.log('qr', qr)
    qrImg.value = qr;
  } catch (err) {
    console.error(err)
  }
}
const config = import.meta.env.VITE_PACKAGE_CONFIG;

watch(() => props.data, async (val, old) => {
  if (Object.keys(val).length) {
    const obj = { ...val };
    const numFile = obj.CeremonyOrdersID;
    const bgMater = numFile + '/' + obj.BackgroundImage;
    const mater = numFile + '/' + obj.BackgroundMaterial;
    const music = numFile + '/' + obj.backgroundMusic;
    const bgMater_online = baseUrl + '/' + obj.BackgroundImage;
    const mater_online = baseUrl + '/' + obj.BackgroundMaterial;
    const music_online = obj.backgroundMusic ? baseUrl + '/' + obj.backgroundMusic : ''
    if (config == 'online') {
      obj.BackgroundImageShow = bgMater_online;
      obj.backgroundMusic = music_online

    } else {

      // if (obj.isBackVideo || obj.isBackImg) {
      //   let bgRes = null;
      //   if (obj.isBackVideo) {
      //     bgRes = await checkVideoExists(bgMater)
      //   }
      //   if (obj.isBackImg) {
      //     bgRes = await checkImgExists(bgMater)
      //   }
      //   if (!bgRes) {
      //     obj.BackgroundImageShow = bgMater_online;
      //   } else {
      //     obj.BackgroundImageShow = bgMater;
      //   }
      // }

      // const music_on = await checkAudioExists(music);

      // if (music_on) {
      //   obj.backgroundMusic = music;
      // } else {
      //   obj.backgroundMusic = music_online
      // }
      poster.value = `${obj.BackgroundImageLocal?.split('.mp4')?.[0]}.jpg`;
      obj.BackgroundImageShow = obj.BackgroundImageLocal;
      obj.backgroundMusic = obj.BackgroundMaterialLocal
    }

    if (obj.BackgroundMaterial) {
      if (config == 'online') {
        obj.BackgroundMaterialShow = mater_online;

      } else {
        // if (obj.isMaterialImg || obj.isMaterialVideo) {
        //   let mRes = null;
        //   if (obj.isMaterialVideo) {
        //     mRes = await checkVideoExists(mater)
        //   }
        //   if (obj.isMaterialImg) {
        //     mRes = await checkImgExists(mater)
        //   }
        //   if (!mRes) {
        //     // images = obj.BackgroundMaterial?.split(',')?.filter(v => v).map(v => (baseUrl + '/' + v))
        //     obj.BackgroundMaterialShow = mater_online;
        //   } else {
        //     obj.BackgroundMaterialShow = mater;
        //   }
        // }

        obj.BackgroundMaterialShow = obj.BackgroundMaterialLocal;
        //obj.BackgroundMaterialShow = numFile + '/' + obj.BackgroundMaterial;
      }
    }
    //测试
    //obj.InteractiveMode = 1;
    //console.log('worship', obj)
    infoData.value = obj;
    const rurl = `${webBaseUrl}/#/?cid=${obj.CeremonyOrdersID}&tid=${obj.ID}`;
    generateQR(rurl)
    // await nextTick();
    // if (audioref.value) {
    //   audioref.value.volume = 0.2
    // }

  }
}, {
  deep: true,
  immediate: true
})



let isAnimating = false;
let pendingUpdateData = null; // 是否有新数据待更新
// 获取大屏互动内容
const getInteractivecontent = async () => {
  if (!infoData.value.CeremonyOrdersID) return;
  try {
    const res = await axios.getAjaxFn('/SZ_CeremonyOrders/GetInteractivecontent', {
      CeremonyOrdersID: infoData.value.ID,
      ID: lid.value
    })

    if (res.length != boxList.value.length) {
      // if (res.length % 5 == 1) {
      //   animations.forEach(anim => anim.kill());
      // }
      const newArr = [...res].reverse()
      if (boxList.value.length == 0) {
        isAnimating = false;
        boxList.value = newArr;
        await nextTick()
        animations.forEach(anim => anim.kill());
        animations = [];
        worshipAnimate(res.length)
      } else {
        pendingUpdateData = newArr;
      }
      
     
    }

  } catch (error) {
    console.log('getTemplateIdFn', error)
  }

}



function getNonOverlappingX(indexInGroup, groupSize) {
  const screenWidth = window.innerWidth;
  const sectionWidth = screenWidth / groupSize;
  const padding = 40;

  const baseX = indexInGroup * sectionWidth + sectionWidth / 2;
  //const variation = (sectionWidth / 2 - padding) * (Math.random() - 0.5); // -~+ 随机偏移
  const variationRange = Math.min(sectionWidth / 2 - padding, 60); // 限制偏移最大60px
  const variation = variationRange * (Math.random() - 0.5);

  return baseX + variation;
}


function worshipAnimate(total) {
  if (isAnimating) return;
  isAnimating = true;
  const GROUP_SIZE = 5;
  //const total = boxList.value.length;
  const groupCount = Math.ceil(total / GROUP_SIZE);
  //console.log('groupCount',groupCount)
  // let currentGroupIndex = groupCount - 1;
  let currentGroupIndex = 0;
  const DURATION = 20; // 动画总时长
  const OVERLAP_TRIGGER_Y = window.innerHeight * 0.1;


  // 所有元素先隐藏
  boxList.value.forEach((_, index) => {
    const el = document.querySelector(`#box_${index}`);
    if (el) {
      gsap.set(el, { opacity: 0 });
    }
  });

  const playGroup = () => {
    //console.log('✅ 所有组播放完成');
    if (currentGroupIndex >= groupCount && groupCount > 1) {
      //console.log('update',groupCount)
      currentGroupIndex = 0;
      playGroup(); // ✅ 继续循环播放
      return;
    }
    // console.log(`▶️ 播放第 ${currentGroupIndex + 1} 组 / 共 ${groupCount} 组`);

    const startIndex = currentGroupIndex * GROUP_SIZE;
    const endIndex = Math.min(startIndex + GROUP_SIZE, total);
    let finishedCount = 0;
    let overlapStarted = false; // 控制 overlap 只触发一次

    for (let i = startIndex; i < endIndex; i++) {
      const el = document.querySelector(`#box_${i}`);
      if (!el) continue;

      const groupIndex = i - startIndex; // 在组内的索引

      const startX = getNonOverlappingX(groupIndex, GROUP_SIZE);
      const endX = startX + (Math.random() * 100 - 50);

      const path = {
        startX,
        endX,
        //startY: infoData.value.HighResolution,
        startY: 200,
        //endY: -infoData.value.HighResolution - 400
        endY: -infoData.value.HighResolution - 200
      };

      gsap.set(el, {
        x: path.startX,
        y: path.startY,
        opacity: 1,
        willChange: "transform",
        force3D: true
      });

      const anim = gsap.to(el, {
        duration: DURATION,
        x: path.endX,
        y: path.endY,
        ease: "linear",
        onStart: () => {
          gsap.set(el, { opacity: 1 });
        },
        onUpdate: async function () {
          // 在播放到一半时，预先启动下一组（只触发一次）
          // if (!overlapStarted && anim.time() >= (DURATION - OVERLAP_TIME)) {
          //   overlapStarted = true;
          //   currentGroupIndex++;
          //   playGroup();
          // }
          if (!overlapStarted) {
            const rect = el.getBoundingClientRect();
            if (rect.top < OVERLAP_TRIGGER_Y) { // 距离顶部不到30%视口
              overlapStarted = true;
              console.log('onUpdate...', groupCount)

              if (pendingUpdateData) {
                animations.forEach(a => a.kill());
                animations = [];
                isAnimating = false;

                boxList.value = pendingUpdateData;
                pendingUpdateData = null;

                await nextTick();
                worshipAnimate(boxList.value.length);
                return;
              }
              currentGroupIndex ++;
              playGroup();
            }
          }
        },
        onComplete: () => {
          //gsap.set(el, { opacity: 0 });
          finishedCount++;
          if (finishedCount === endIndex - startIndex) {
            //console.log('onComplete...',finishedCount)

            if (groupCount === 1) {
              console.log('onComplete...groupCount', groupCount)
              currentGroupIndex = 0;
              playGroup();
            }

          }
        }
      });

      animations.push(anim);
    }
  };

  // ✅ 首组立即播，并跳过 overlap 逻辑
  playGroup();
}




onMounted(async () => {
  timer = setInterval(() => {
    getInteractivecontent()
  }, 2 * 1000)
})

onBeforeUnmount(() => {
  clearInterval(timer)
  animations.forEach(animation => animation.kill());
})
</script>
<style lang="less" scoped>
@w: 1920vw;
@rw: (@w/100);
@h: 1080vh;
@rh: (@h/100);

.adaptive-size(@elementWidth, @elementHeight, @baseWidth: 1920, @baseHeight: 1080) {
  @widthRatio: (@elementWidth / @baseWidth) * 100;
  @heightRatio: (@elementHeight / @baseHeight) * 100;
  width: @widthRatio * 1vw;
  height: @heightRatio * 1vh;
}

.adaptive-font(@elementWidth, @baseWidth: 1920) {
  @widthRatio: (@elementWidth / @baseWidth) * 100;
  font-size: @widthRatio * 1vw;
}

.wrap {
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: border-box;

  .mater {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    object-fit: contain;
    /* 确保视频填满屏幕，且保持视频比例 */
    object-position: center;
    background-color: transparent;
    /* 背景颜色，避免视频比例问题时的黑边 */
    z-index: 3;
  }
}

.worship-item {
  width: 122px;
  height: 194px;
  background: url('../assets/img/dl2.png') no-repeat;
  background-size: 100% 100%;
  position: absolute;
  bottom: 0;
  will-change: transform;
  transform-style: preserve-3d;
  //left: 50%; // 确保初始位置是相对于屏幕中心的
  //transform: translateX(-50%); // 确保元素初始位置在屏幕两侧随机分布
  //display: none; // 初始时隐藏
  z-index: 1;

  &.start_bg {
    // width: (122vw / @rw);
    // height: (122vw / @rw);
    width: 122px;
    height: 122px;
    background: url('../assets/img/start_bg.jpg') no-repeat;
    background-size: 100% 100%;
  }

  .text-wrap {
    position: absolute;
    width: (200vw / @rw);
    //width: 200px;
    height: fit-content;
    padding: 5px 10px;
    top: 70%;
    left: 50%;
    transform: translateX(-50%);
    border: 2px solid rgb(252, 135, 51);
    border-radius: 4px;
    .adaptive-font(14);
    color: #000;
    background: rgb(255, 227, 205);
    box-sizing: border-box;
    z-index: 6;

    .left {
      .adaptive-font(16);
      font-weight: bold;
    }

    .content {
      text-indent: 20px;
    }

    .right {
      text-align: right;
    }
  }

}

.qrcode {
  position: absolute;
  left: 200px;
  top: 50%;
  transform: translateY(-50%);
  //width: 150px;
  width: (80vw / @rw);
  height: (80vw / @rw);
  z-index: 1;

  &.qrcode_right {
    left: initial;
    right: 200px;
  }
}

.video_bg {
  position: absolute;
  left: 0;
  top: 0;
  z-index: -2;
  //object-fit: cover; /* 确保视频填满屏幕，且保持视频比例 */
  background-color: transparent;
  /* 背景颜色，避免视频比例问题时的黑边 */
  /* 背景颜色，避免视频比例问题时的黑边 */
}

.audio_wrap {
  position: absolute;
  right: 0;
  top: 0;
  display: none;
}

@media screen and (max-width:1920px) {
  .qrcode {
    width: 150px;
    height: 150px;
  }
}
</style>